<template>
  <div class="box">
    <div class="search">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input v-model="pageParams.userName" placeholder="请输入用户名" />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button type="primary" @click="show">新增</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="table">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" width="50" />
        <el-table-column prop="userName" label="用户名" width="180" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="createdAt" label="创建时间" />
        <el-table-column label="操作" min-width="120">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" circle @click="edit(scope.row)" />
            <el-button type="danger" :icon="Delete" circle @click="del(scope.row.id)" />
            <el-button type="warning" circle>
              <el-icon>
                <View />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <page :pageParams="pageParams" :total="total" @sizeChange="pageChange" @current-change="changeCurrent"></page>
    <el-dialog v-model="dialogVisible" :title="title" width="40%">
      <div>
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="ruleForm.userName" />
          </el-form-item>
          <el-form-item label="密码" prop="passWord" v-if="title == '新增'">
            <el-input v-model="ruleForm.passWord" />
          </el-form-item>
          <el-form-item label="权限" prop="role">
            <el-select v-model="ruleForm.role" placeholder="Select">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="管理员姓名" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              确定
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref, } from 'vue';
import { list, add, userdel, detail, updated } from '../api/list1'
import { Delete, Edit } from '@element-plus/icons-vue'
import page from '@/components/page.vue';
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'

const title = ref('')
const dialogVisible = ref(false)
const options = [{
  label: '超级管理员',
  value: 1
},
{
  label: '管理员',
  value: 2
}, {
  label: '普通用户',
  value: 3
}]
const tableData: any = ref([])
const pageParams = reactive({
  page: 1,
  rows: 10,
  userName: ''
})
const id = ref(0)
const total = ref(0)
onMounted(() => {
  getList()
})
// 列表
function getList() {
  list(pageParams).then(res => {
    console.log(res);
    tableData.value = res.data.list
    total.value = res.data.count
  })
}
function search() {
  pageParams.page = 1
  getList()
}

// 分页 子传父接收数据 
// 条数改变时
function pageChange(val: number) {
  pageParams.rows = val
  pageParams.page = 1
  getList()
}

function changeCurrent(val: number) {
  pageParams.page = val
  getList()
}

// 打开弹框
function show() {
  title.value = '新增'
  dialogVisible.value = true
  nextTick(() => {
    ruleFormRef.value?.resetFields()
  })
}

interface RuleForm {
  name: string
  userName: string
  passWord: string
  role: number
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  name: '',
  userName: '',
  passWord: '123456',
  role: 3
})


const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
  ],
  userName: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
  ],
  role: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
  ],
  passWord: [
    { required: true, message: 'Please input Activity name', trigger: 'blur' },
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (title.value == '新增') {
        // 新增窗口
        add(ruleForm).then(res => {
          ElMessage({
            message: '新增成功',
            type: 'success',
            plain: true,
          })
          dialogVisible.value = false
        })
          .catch(err => {
            if (err.code == 188) {
              ElMessage({
                message: '用户名已存在',
                type: 'error',
                plain: true,
              })
            }
          })
      } else {
        updated({
          id: id.value,
          ...ruleForm
        }).then(res => {
          ElMessage({
            message: '修改成功',
            type: 'success',
            plain: true,
          })
          getList()
          dialogVisible.value = false
        })
      }

    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

function del(val: number) {
  userdel({ id: val }).then(res => {
    ElMessage({
      message: '删除成功',
      type: 'success',
      plain: true,
    })
    getList()
  })
}

function edit(row: any) {
  dialogVisible.value = true
  title.value = '编辑'
  // 通过查询获得当前行信息 查找id
  // 获取详情
  detail(row.id).then(res => {
    console.log(res)
    ruleForm.name = res.data.name
    ruleForm.userName = res.data.userName
    ruleForm.role = res.data.role
    ruleForm.name = res.data.name
    id.value = res.data.id
  })
}
</script>

<style scoped>
.box {
  padding: 20px;
}

.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>